//
//  UIViewController+RSPhoto.m
//  GuangXiElectricityNet
//
//  Created by thinkjoy on 16/6/27.
//  Copyright © 2016年 thinkjoy. All rights reserved.
//

#import "UIViewController+RSPhoto.h"
#import "objc/runtime.h"
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

#ifdef DEBUG
#define debugLog(...)    NSLog(__VA_ARGS__)
#else
#define debugLog(...)
#endif

static  BOOL canEdit = NO;
static  BOOL saveToPhone = NO;
static  char blockKey;

typedef void(^AlertViewAction)(UIAlertAction *action);
typedef void(^AlertViewOtherAction)(UIAlertAction *action);

/**
 *  点击的按钮,默认为0
 *  1 点击相册
 *  2 点击相机
 */
static int buttonIndex = 0;

@interface UIViewController()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIAlertViewDelegate>

@property (nonatomic,copy)photoBlock photoBlock;

@end

@implementation UIViewController (RSPhoto)

#pragma mark-set
-(void)setPhotoBlock:(photoBlock)photoBlock
{
    objc_setAssociatedObject(self, &blockKey, photoBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark-get
- (photoBlock )photoBlock
{
    return objc_getAssociatedObject(self, &blockKey);
}

-(void)showCanEdit:(BOOL)edit saveToPhone:(BOOL)save photo:(photoBlock)block
{
    if(edit) canEdit = edit;
    if (save) saveToPhone = save;
    
    self.photoBlock = [block copy];
    
    //创建弹框
    __unsafe_unretained __typeof(self)    weakSelf    =   self;
    [self showAlertViewWithControllerTitle:nil message:nil controllerStyle:UIAlertControllerStyleActionSheet isHaveTextField:NO actionTitle:@"打开相机" actionStyle:UIAlertActionStyleDefault alertViewAction:^(UIAlertAction *action) {
        
        [weakSelf    clickActionWithButtonIndex:2];
        buttonIndex =   2;
    } otherActionTitle:@"打开相册" otherActionStyle:UIAlertActionStyleDefault otherAlertViewAction:^(UIAlertAction *action) {
        
        [weakSelf    clickActionWithButtonIndex:1];
        buttonIndex =   1;
    } threeActionTitle:@"取消" threeActionStyle:UIAlertActionStyleCancel threeAlertViewAction:^(UIAlertAction *action) {
        buttonIndex =   -1;
    }];
    
}

- (void)clickActionWithButtonIndex:(NSInteger )buttonIndex
{
    //相册权限
    PHAuthorizationStatus   typeStatus  = 0;

    //相机权限
    AVAuthorizationStatus author2 = 0;
    if (buttonIndex==2) {
        author2  =   [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    }else if (buttonIndex==1)
    {
//        author1 = [ALAssetsLibrary authorizationStatus];
        typeStatus  =     [PHPhotoLibrary authorizationStatus];
    }
    
    if (typeStatus==PHAuthorizationStatusRestricted ||
        typeStatus==PHAuthorizationStatusDenied ||
//        typeStatus== PHAuthorizationStatusNotDetermined ||
//        author2 == AVAuthorizationStatusNotDetermined ||
        author2 ==AVAuthorizationStatusRestricted ||
        author2== AVAuthorizationStatusDenied) {
//        CGFloat kSystemMainVersion = [UIDevice currentDevice].systemVersion.floatValue;
        NSString *title = nil;
        NSString *photoType = buttonIndex==0?@"相机":@"相册";
        NSString *msg = [NSString stringWithFormat:@"还没有开启%@权限,请在系统设置中开启",photoType];
        NSString *cancelTitle = @"暂不";
        NSString *otherButtonTitles = @"去设置";
        
//        if (kSystemMainVersion < 8.0) {
        title = [NSString stringWithFormat:@"%@权限未开启",photoType];
        msg = [NSString stringWithFormat:@"请在系统设置中开启%@服务\n(设置>隐私>%@>开启)",photoType,photoType];
        cancelTitle = @"知道了";
        otherButtonTitles = nil;
        
        [self  showAlertViewWithControllerTitle:title message:msg controllerStyle:UIAlertControllerStyleAlert isHaveTextField:NO actionTitle:cancelTitle actionStyle:UIAlertActionStyleCancel alertViewAction:^(UIAlertAction *action) {
            
        }];
        
        return ;
    }
    
    //跳转到相机/相册页面
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = canEdit;
    switch (buttonIndex)
    {
        case 2:
            //拍照
            //是否支持相机
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                if([[[UIDevice
                      currentDevice] systemVersion] floatValue]>=8.0) {
                    
                    self.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                    
                }
                [self presentViewController:imagePickerController animated:YES completion:NULL];
                
            }
            else
            {
                [self  showAlertViewWithControllerTitle:@"温馨提示" message:@"该设备不支持相机" controllerStyle:UIAlertControllerStyleAlert isHaveTextField:NO actionTitle:@"确定" actionStyle:UIAlertActionStyleCancel alertViewAction:^(UIAlertAction *action) {
                    
                }];
            }
            break;
        case 1:
            //相册
            imagePickerController.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        default:
            break;
    }

}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//    NSLog(@"didFinishPickingMediaWithInfo==%@",info);
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image;
    //是否要裁剪
    if ([picker allowsEditing]){
        
        //编辑之后的图像
        image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (saveToPhone&&buttonIndex==2) {//允许保存且是相机拍到的图片
            [self tapToIphoneSaveImage:image];
        }
    } else {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (saveToPhone&&buttonIndex==2) {//允许保存且是相机拍到的图片
            [self tapToIphoneSaveImage:image];
        }
    }
    
    if(self.photoBlock)
    {
        self.photoBlock([self fixOrientation:image]);
    }
}

#pragma mark    只有一个action
/**
 *  创建一个只有一个action
 *
 *  @param controllerTitle 警告框标题
 *  @param message         提示信息
 *  @param controllerStyle 样式
 *  @param isHaveTextField 是否需要一个输入框
 *  @param actionTitle     按钮信息
 *  @param actionStyle     按钮样式
 *  @param alertViewAction block名字
 */
- (void)showAlertViewWithControllerTitle:(NSString *)controllerTitle
                                 message:(NSString *)message
                         controllerStyle:(UIAlertControllerStyle)controllerStyle
                         isHaveTextField:(BOOL)isHaveTextField
                             actionTitle:(NSString *)actionTitle
                             actionStyle:(UIAlertActionStyle)actionStyle
                         alertViewAction:(AlertViewAction)alertViewAction {
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:controllerTitle message:message preferredStyle:controllerStyle];
    if (isHaveTextField == YES) {
        [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
    }
    UIAlertAction *alertOne = [UIAlertAction actionWithTitle:actionTitle style:actionStyle handler:^(UIAlertAction * _Nonnull action)  {
        alertViewAction(action);
    }];
    [alertC addAction:alertOne];

    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
}

#pragma mark    创建一个有三个action
/**
 *  创建一个有两个action
 *
 *  @param controllerTitle 警告框标题
 *  @param message         提示信息
 *  @param controllerStyle 样式
 *  @param isHaveTextField 是否需要一个输入框
 *  @param actionTitle          按钮信息
 *  @param actionStyle          按钮样式
 *  @param alertViewAction      block名字
 *  @param otherActionTitle     按钮信息
 *  @param otherActionStyle     按钮样式
 *  @param otherAlertViewAction block名字
 */
- (void)showAlertViewWithControllerTitle:(NSString *)controllerTitle
                                 message:(NSString *)message
                         controllerStyle:(UIAlertControllerStyle)controllerStyle
                         isHaveTextField:(BOOL)isHaveTextField
                             actionTitle:(NSString *)actionTitle
                             actionStyle:(UIAlertActionStyle)actionStyle
                         alertViewAction:(AlertViewAction)alertViewAction
                        otherActionTitle:(NSString *)otherActionTitle
                        otherActionStyle:(UIAlertActionStyle)otherActionStyle
                    otherAlertViewAction:(AlertViewOtherAction)otherAlertViewAction
                        threeActionTitle:(NSString *)threeActionTitle
                        threeActionStyle:(UIAlertActionStyle)threeActionStyle
                    threeAlertViewAction:(AlertViewOtherAction)threeAlertViewAction
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:controllerTitle message:message preferredStyle:controllerStyle];
    if (isHaveTextField == YES) {
        [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
    }
    UIAlertAction *alertOne = [UIAlertAction actionWithTitle:actionTitle style:actionStyle handler:^(UIAlertAction * _Nonnull action)  {
        alertViewAction(action);
    }];
    UIAlertAction *alertTwo = [UIAlertAction actionWithTitle:otherActionTitle style:otherActionStyle handler:^(UIAlertAction * _Nonnull action)  {
        otherAlertViewAction(action);
    }];
    UIAlertAction *alertThree = [UIAlertAction actionWithTitle:threeActionTitle style:threeActionStyle handler:^(UIAlertAction * _Nonnull action)  {
        threeAlertViewAction(action);
    }];
    [alertC addAction:alertOne];
    [alertC addAction:alertTwo];
    [alertC addAction:alertThree];
    
    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
    
}

#pragma mark    检测图片的orientation属性,转为0
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

#pragma mark    保存使用相机拍到的图片
- (void)tapToIphoneSaveImage:(UIImage *)img
{
    
    /**
     *  将图片保存到iPhone本地相册
     *  UIImage *image            图片对象
     *  id completionTarget       响应方法对象
     *  SEL completionSelector    方法
     *  void *contextInfo
     */
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    if (error == nil) {
        
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil nil];
        //        [alert show];
        NSLog(@"存储成功");
    }else{
        
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil nil];
        //        [alert show];
        NSLog(@"存储失败");
    }
    
}


@end
